<template>
    <div>
        <el-form-item label="提示文字">
            <el-input size="default" v-model="modelValue.placeholder" placeholder="请设置提示语" />
        </el-form-item>
        <!-- <el-form-item label="是否多选" required>
            <el-input size="default" v-model="modelValue.isMultiple" placeholder="选择器是否多选" />
        </el-form-item> -->
        <el-form-item label="表格绑定" required>
            <el-input size="default" v-model="modelValue.tables"  placeholder="需要赋值绑定的表格"/>
        </el-form-item>
        <el-form-item label="配数据源" required>
            <el-button icon="link" @click="visible = true">编辑http数据源</el-button>
        </el-form-item>
        <el-form-item class="options">
            <template #label>
                <div class="option-item-label">
                    <span>选项设置（鼠标拖拽排序）</span>
                    <el-button icon="plus" link type="primary"
                        @click="modelValue.optionText.push({ name: '', value: '' })">新增选项
                    </el-button>
                </div>
            </template>
            <draggable item-key="id" v-model="modelValue.optionText" class="option-items"
                :component-data="{ tag: 'div', type: 'transition-group' }" handler=".el-icon-rank" v-bind="dragOption">
                <template #item="{ element, index }">
                    <div class="option-item" style=" display: flex;flex-direction: row;">
                        <el-input v-model="element.value" style="width: 120px;" placeholder="字典项值名称" clearable />
                        ~
                        <el-input v-model="element.name" :placeholder="element.placeholder" style="width: 120px;" />
                        <el-icon class="del-btn" @click="modelValue.optionText.splice(index, 1)">
                            <delete />
                        </el-icon>
                    </div>
                </template>
            </draggable>
        </el-form-item>
        <w-dialog title="配置http数据源请求" width="600px" v-model="visible" @opened="loadHttp" @ok="httpOk">
            <http-req ref="http" :runtime="false" :show-tip="false" v-model="tempHttp">
                <template #aft>
                    <el-radio-group v-model="tempHttp.aftHandler.isJs" style="margin-bottom: 10px">
                        <el-radio :label="false">规则解析</el-radio>
                        <el-radio :label="true">JS解析(小程序端不支持)</el-radio>
                    </el-radio-group>
                    <div v-if="!tempHttp.aftHandler.isJs">
                        <el-input style="width: 150px;" v-model="tempHttp.aftHandler.rule.source"><template
                                slot="prepend">返回值.</template></el-input>
                        取数据
                        <el-input style="width: 150px;" v-model="tempHttp.aftHandler.rule.name"><template
                                slot="prepend">名称</template></el-input>---
                        <el-input style="width: 150px;" v-model="tempHttp.aftHandler.rule.value"><template
                                slot="prepend">值</template></el-input>
                    </div>
                    <code-editor v-else height="200px" ref="aftCode" v-model="tempHttp.aftHandler.js"
                        :default-value="`function aftHandler(rsp){\n\t//获取到结果后做一些处理\n\t\n}`" />
                </template>
            </http-req>
        </w-dialog>
    </div>
</template>

<script>
import HttpReq from "@/components/common/HttpReq.vue";
import draggable from "vuedraggable";
import ConfigMinxins from '../ConfigMinxins.js'
import CodeEditor from '@/components/common/CodeEditor.vue'

export default {
    name: 'TextSelectorConfig',
    mixins: [ConfigMinxins],
    components: { draggable, HttpReq, CodeEditor },
    props: {
        modelValue: {
            type: Object,
            default: () => {
                return {}
            },
        },
    },
    data() {
        return {
            visible: false,
            tempHttp: {
                url: '',
                method: 'GET',
                headers: [],
                contentType: 'JSON',
                params: [],
                data: '',
                preHandler: null,
                aftHandler: {
                    isJs: false,
                    js: '',
                    rule: {
                        source: '',
                        name: '',
                        value: ''
                    }
                }
            },
            dragOption: {
                animation: 300,
                sort: true,
                group: 'option'
            },
        }
    },
    beforeMount() {
        this.loadHttp()
      console.log(this.modelValue,'this.modelValue')
    },
    methods: {
        loadHttp() {
            this.tempHttp = this.$deepCopy(this.modelValue.http)
            //处理旧数据兼容
            const aftHandler = {
                isJs: true,
                js: '',
                rule: {
                    source: 'data',
                    name: 'name',
                    value: 'value'
                }
            }
            if (typeof (this.tempHttp.aftHandler) === 'string') {
                // aftHandler.js = this.tempHttp.aftHandler
                this.tempHttp['aftHandler'] = aftHandler
            } else if (!this.tempHttp.aftHandler) {
                this.tempHttp['aftHandler'] = aftHandler
            }
            if (this.$refs.aftCode) {
                this.$refs.aftCode.reloadCode()
            }
        },
        //数组转对象
        coverParams(args, isForm = false) {
            let params = {};
            if (Array.isArray(args)) {
                args.forEach(arg => {
                    if (this.$isNotEmpty(arg.name)) {
                        params[arg.name] = arg.value.replace(/\$\{(\w+)\}/g, (match, key) => {
                            // 特殊处理 ${lang}
                            if (key === 'lang') {
                              return localStorage.getItem('lang')?.includes('中文') ? 'zh-CN' : localStorage.getItem('lang')?.includes('English')?'en-US':'es-MX';
                            }
                            return '';
                        })
                    }
                })
            } else {
                params = { ...args }
            }
            if (isForm) {
                return Object.keys(params).map(v => `${v}=${params[v]}`).join('&')
            }
            return params
        },
        httpOk() {
            // 获取字典字段并绑定到表单
            this.$refs.http.validate((valid, err) => {
                if (valid) {
                    this.modelValue.http = this.$deepCopy(this.tempHttp)
                    this.visible = false
                } else {
                    this.$message.warning(err)
                }
            })
            const params = {
                url: this.modelValue.http.url,
                method: this.modelValue.http.method.toLowerCase(),
                headers: {
                    'Content-Type': this.modelValue.http.contentType === 'JSON' ? 'application/json' : 'application/x-www-form-urlencoded'
                },
                params: this.coverParams(this.modelValue.http.params || []),
                data: this.modelValue.http.contentType === 'JSON' ? JSON.parse(this.bindVar(this.modelValue.http.data || '{}')) : ''
            }
            this.$axios.request(params).then(rsp => {
              console.log(rsp,'rsp')
              console.log(rsp.data.model,'rsp')
                Object.keys(rsp.data.model).forEach(item => {
                    let length = this.modelValue.optionText.filter(x => x.value == item);
                    if(length == 0){
                        this.modelValue.optionText.push({ value: item, name: '', placeholder: rsp.data.model[item] })
                    }
                })
                this.modelValue.optionText.forEach(item => {
                    let length = Object.keys(rsp.data.model).filter(x => x == item.value);
                    if (length == 0) {
                        // 如果 rsp.data.model 中没有找到 item，将其从 modelValue.options 中移除
                        // 这里可以使用 Vue 的响应式数据更新机制进行处理
                        this.modelValue.optionText = this.modelValue.optionText.filter(i => i !== item);
                    }
                })
            }).catch(err => {
                // this.loading = false
                this.$message.warning('暂无数据')
            })
        },
    },
    emits: ['update:modelValue'],
}
</script>

<style scoped lang="less">
:deep(.options) {
    display: flex;
    flex-direction: column;

    .el-form-item__label {
        width: 100% !important;
    }

    .option-item {
        margin-bottom: 5px;
    }

    .del-btn {
        cursor: pointer;
        margin-left: 5px;
        padding: 5px;
        border-radius: 50%;

        &:hover {
            background: #DDDFE5;
        }
    }
}


.option-item-label {
    display: flex;
    text-align: left;

    button {
        float: right;
    }
}
</style>
